package cn.wolfcode.wms.controller;

import cn.wolfcode.wms.domain.Role;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.service.IRoleService;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.vo.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private ISystemMenuService systemMenuService;

    @RequestMapping("/list")
    @RequiredPermission("角色列表")
    public String list(QueryObject qo, Map map) {
        map.put("pageResult", roleService.query(qo));
        return "role/list";
    }

    @RequestMapping("/input")
    @RequiredPermission("角色编辑")
    public String input(Long id, Map map) {
        map.put("permissions", permissionService.listAll());
        map.put("menus", systemMenuService.listAll());
        if (id != null) {
            map.put("role", roleService.getById(id));
        }
        return "role/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission("更新或新增角色")
    @ResponseBody
    public JSONResult saveOrUpdate(Role role, Long[] ids, Long[] menuIds) {
        try {
            roleService.saveOrUpdate(role, ids, menuIds);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.mark(e.getMessage());
        }
        return JSONResult.success("操作成功！");
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission("删除角色")
    public JSONResult delete(Long id) {
        try {
            roleService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            // 出错时返回错误信息
            return JSONResult.mark(e.getMessage());
        }
        return JSONResult.success("删除成功！");
    }
}
